package com.bringspring.extend.utils;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.bringspring.common.base.ActionResult;
import com.bringspring.common.exception.DataException;
import com.bringspring.common.util.JsonUtil;
import com.bringspring.common.util.StringUtils;
import com.bringspring.system.base.entity.DictionaryDataEntity;
import com.bringspring.system.base.entity.ProvinceEntity;
import com.bringspring.system.base.exception.WorkFlowException;
import com.bringspring.system.base.model.dataInterface.DataInterfaceActionVo;
import com.bringspring.system.base.service.BillRuleService;
import com.bringspring.system.base.service.DataInterfaceService;
import com.bringspring.system.base.service.DictionaryDataService;
import com.bringspring.system.base.service.ProvinceService;
import com.bringspring.system.permission.entity.OrganizeEntity;
import com.bringspring.system.permission.entity.PositionEntity;
import com.bringspring.system.permission.entity.UserEntity;
import com.bringspring.system.permission.service.OrganizeService;
import com.bringspring.system.permission.service.PositionService;
import com.bringspring.system.permission.service.UserService;
import com.bringspring.system.permission.util.PermissionUtil;
import com.bringspring.workflow.engine.entity.FlowTaskEntity;
import com.bringspring.workflow.engine.service.FlowTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 数据转换(代码生成器用)
 *
 * @author 开发平台组
 * @version V1.0.0
 * @copyright 股份有限公司
 * @date 2021/3/16
 */
@Component
public class DictionaryConversion {

	@Autowired
	private OrganizeService organizeService;

	@Autowired
	private PositionService positionService ;

	@Autowired
	private UserService userService ;


	@Autowired
	private DataInterfaceService dataInterfaceService ;


	@Autowired
	private ProvinceService provinceService;

	@Autowired
	private DictionaryDataService dictionaryDataService;

	@Autowired
	private BillRuleService billRuleService;

	@Autowired
	private FlowTaskService flowTaskService;

	public final String regEx = "[\\[\\]\"]";
	/**
	 * 日期时间戳字符串转换
	 *
	 * @param date
	 * @param format
	 * @return
	 */
	public String dateSwap(String date, String format) {
		if (StringUtils.isNotEmpty(date)) {
			DateTimeFormatter ftf = DateTimeFormatter.ofPattern(format);
			if (date.contains(",")) {
				String[] dates = date.split(",");
				long time1 = Long.parseLong(dates[0]);
				long time2 = Long.parseLong(dates[1]);
				String value1 = ftf.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(time1), ZoneId.systemDefault()));
				String value2 = ftf.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(time2), ZoneId.systemDefault()));
				return value1 + "至" + value2;
			}
			long time = Long.parseLong(date);
			String value = ftf.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(time), ZoneId.systemDefault()));
			return value;
		}
		return date;
	}

	/**
	 * 行政区划转换
	 *
	 * @param data
	 * @return
	 */
	public String provinceData(String data) {
		if (StringUtils.isNotEmpty(data)) {
			try {
				if (data.contains("[[")){
					List<String> addList = new ArrayList<>();
					String[][] provinceDataS = JsonUtil.getJsonToBean(data, String[][].class);
					for (String[] AddressData :provinceDataS){
						List<String> provList = new ArrayList(Arrays.asList(AddressData));
						List<ProvinceEntity> proList = provinceService.getProList(provList);
						//单条
						List<String> adList = proList.stream().map(pro->pro.getFullName()).collect(Collectors.toList());
						addList.add(String.join("/", adList));
					}
					return String.join(";",addList);
				}else if (data.contains("[")) {
					List<String> idList = JsonUtil.getJsonToList(data, String.class);
					List<String> nameList = new ArrayList<>();
					for (String orgId : idList) {
						ProvinceEntity info = provinceService.getInfo(orgId);
						nameList.add(Objects.nonNull(info) ? info.getFullName() : orgId);
					}
					return String.join("/",nameList);
				}/*else if(data.getBytes().length != data.length()){
					String areaIds = provinceService.getAreaIds(data);
					return data;
				}*/
				else {
					String[] strs = data.split(",");
					List<String> provList = new ArrayList(Arrays.asList(strs));
					List<String> proNameList = new ArrayList<>();
					List<ProvinceEntity> proList = provinceService.getProList(provList);
					for (ProvinceEntity entity : proList){
						proNameList.add(entity.getFullName());
					}
					return String.join("/",proNameList);
				}
			}catch (Exception e){
				e.printStackTrace();
			}
		}
		return "";
	}

	/**
	 * 所属组织id转名称
	 *
	 * @param value
	 * @return
	 */
	public String comSelectValue(String value,String showLevel) {
		if (StringUtils.isNotEmpty(String.valueOf(value))) {
			OrganizeEntity organizeEntity = organizeService.getInfo(String.valueOf(value));
			if ("all".equals(showLevel)) {
				value= PermissionUtil.getLinkInfoByOrgId(value, organizeService, false);
			} else {
				if (organizeEntity != null) {
					value = organizeEntity.getFullName();
				}
			}
		}
		return value;
	}

	/**
	 * 公司部门id转名称(多选)
	 *
	 * @param ids
	 * @return
	 */
	public String comSelectValues(String ids) {
		List<String> comValueList= new ArrayList<>();
		if (StringUtils.isEmpty(ids)){
			return null;
		}
		if (ids.contains("[[")){
			String[][] idArrays = JsonUtil.getJsonToBean(ids, String[][].class);
			for (String[] array : idArrays){
				List<String> idList = new ArrayList<>();
				for (String s : array){
					OrganizeEntity info = organizeService.getInfo(s);
					idList.add(Objects.nonNull(info) ? info.getFullName() : s );
				}
				String orgCom = idList.stream().collect(Collectors.joining("/"));
				comValueList.add(orgCom);
			}
			return comValueList.stream().collect(Collectors.joining(";"));
		}else if (ids.contains("[")){
			List<String> idList=JsonUtil.getJsonToList(ids,String.class);
			List<String> nameList= new ArrayList<>();
			for (String orgId : idList){
				OrganizeEntity info = organizeService.getInfo(orgId);
				nameList.add(Objects.nonNull(info) ? info.getFullName() : orgId);
			}
			return nameList.stream().collect(Collectors.joining("/"));
		}else {
			ids = ids.replaceAll("\"","");
			String[] idList = ids.split(",");
			if (idList.length > 0) {
				List<String> comSelectList = new ArrayList<>();
				for (String id : idList) {
					OrganizeEntity organizeEntity = organizeService.getInfo(id);
					if (organizeEntity != null) {
						comSelectList.add(organizeEntity.getFullName());
					}
				}
				return String.join("/", comSelectList);
			}
		}
		return null;
	}


	/**
	 * 岗位id转名称
	 *
	 * @param id
	 * @return
	 */
	public String posSelectValue(String id) {
		if (StringUtils.isNotEmpty(id)) {
			PositionEntity positionServiceInfo = positionService.getInfo(id);
			if (ObjectUtil.isNotEmpty(positionServiceInfo)) {
				return positionServiceInfo.getFullName();
			}
			return id;
		}
		return "";
	}

	/**
	 * 岗位id转名称(多选)
	 *
	 * @param ids
	 * @return
	 */
	public String posSelectValues(String ids) {
		if (StringUtils.isEmpty(ids)){
			return "";
		}
		List<String> posList = new ArrayList<>();
		if (ids.contains("[")){
			List<String> idList=JsonUtil.getJsonToList(ids,String.class);
			List<String> nameList= new ArrayList<>();
			for (String orgId : idList){
				PositionEntity info = positionService.getInfo(orgId);
				nameList.add(Objects.nonNull(info) ? info.getFullName() : orgId);
			}
			posList = nameList;
		}else {
			String[] idList = ids.split(",");
			if (idList.length > 0) {
				for (String id : idList) {
					PositionEntity positionEntity = positionService.getInfo(id);
					if (ObjectUtil.isNotEmpty(positionEntity)) {
						posList.add(positionEntity.getFullName());
					}
				}
			}
		}
		return String.join("/", posList);
	}

	/**
	 * 用户id转名称
	 *
	 * @param id
	 * @return
	 */
	public String userSelectValue(String id) {
		if (StringUtils.isNotEmpty(id)) {
			UserEntity userEntity = userService.getInfo(id);
			if (ObjectUtil.isNotEmpty(userEntity)) {
				return userEntity.getRealName() + "/" + userEntity.getAccount();
			}
			return id;
		}
		return "";
	}

	public String userSelectValueNoAccount(String id) {
		if (StringUtils.isNotEmpty(id)) {
			UserEntity userEntity = userService.getInfo(id);
			if (ObjectUtil.isNotEmpty(userEntity)) {
				return userEntity.getRealName() ;
			}
			return id;
		}
		return "";
	}
	/**
	 * 用户id转名称(多选)
	 *
	 * @param ids
	 * @return
	 */
	public String userSelectValues(String ids) {
		if (StringUtils.isEmpty(ids)) {
			return ids;
		}
		if (ids.contains("[")){
			List<String> nameList = new ArrayList<>();
			List<String> jsonToList = JsonUtil.getJsonToList(ids, String.class);
			for (String userId : jsonToList){
				UserEntity info = userService.getInfo(userId);
				nameList.add(Objects.nonNull(info) ? info.getRealName()+ "/" + info.getAccount() : userId);
			}
			return String.join(";", nameList);
		}else {
			List<String> userInfoList = new ArrayList<>();
			String[] idList = ids.split(",");
			if (idList.length > 0) {
				for (String id : idList) {
					UserEntity userEntity = userService.getInfo(id);
					if (ObjectUtil.isNotEmpty(userEntity)) {
						String info = userEntity.getRealName() + "/" + userEntity.getAccount();
						userInfoList.add(info);
					}
				}
			}
			return String.join("-", userInfoList);
		}
	}

	/**
	 * 开关
	 *
	 * @param data
	 * @return
	 */
	public String switchSelectValue(String data,String activeTxt,String inactiveTxt) {
		if (StringUtils.isNotEmpty(data)) {
			if (data.equals("0") || data.equals("false")) {
				return inactiveTxt;
			} else if (data.equals("1") || data.equals("true")) {
				return activeTxt;
			} else {
				return data;
			}
		}
		return null;
	}



	/**
	 * 弹窗
	 *
	 * @param interfaceId
	 * @param propsValue
	 * @param relationField
	 * @param dataValue
	 * @return
	 */
	public String getPopupSelectValue(String interfaceId, String propsValue, String relationField, String dataValue,Map<String, Object> dataMaps) {
		if (StringUtils.isNotEmpty(dataValue)) {
			Object data = dataInterfaceService.infoToId(interfaceId).getData();
			List<Map<String, Object>> dataInterfaceDataList;
			if (data instanceof DataInterfaceActionVo){
				DataInterfaceActionVo actionVo = (DataInterfaceActionVo) data;
				dataInterfaceDataList = (List<Map<String, Object>>) actionVo.getData();
			}else {
				dataInterfaceDataList = (List<Map<String, Object>>) data;
			}
			Map<String, Object>	dataMap = dataInterfaceDataList.stream().filter(d -> d.get(propsValue).equals(dataValue)).findFirst().orElse(null);
			if (dataMap!=null){
				dataMaps.putAll(dataMap);
				return String.valueOf(dataMap.get(relationField));
			}
			return null;
		} else {
			return null;
		}
	}


	public String getFileNameInJson(String fileJson){
		if (StringUtils.isNotEmpty(fileJson) && !"null".equals(fileJson) ){
			return fileJson;
		}
		return "";
	}

	/**
	 * 获取数据字典数据
	 *
	 * @param feild
	 * @return
	 */
	public String getDicName(String feild,String dictionaryTypeId) {
		if (StringUtils.isNotEmpty(feild)) {
			//去除中括号以及双引号
			feild = feild.replaceAll(regEx, "");
			//判断多选框
			String[] feilds = feild.split(",");
			if (feilds.length > 1) {
				StringBuilder feildsValue = new StringBuilder();
				DictionaryDataEntity dictionaryDataEntity;
				for (String feil : feilds) {
					dictionaryDataEntity = dictionaryDataService.getSwapInfo(feil,dictionaryTypeId);
					if (dictionaryDataEntity != null) {
						feildsValue.append(dictionaryDataEntity.getFullName() + ",");
					}
				}
				String finalValue;
				if (StringUtils.isEmpty(feildsValue) || feildsValue.equals("")) {
					finalValue = feildsValue.toString();
				} else {
					finalValue = feildsValue.substring(0, feildsValue.length() - 1);
				}
				return finalValue;
			}
			DictionaryDataEntity dictionaryDataentity = dictionaryDataService.getSwapInfo(feild,dictionaryTypeId);
			if (dictionaryDataentity != null) {
				return dictionaryDataentity.getFullName();
			}
			return feild;
		}
		return feild;
	}

	/**
	 * 获取远端数据
	 *
	 * @param urlId
	 * @param label
	 * @param value
	 * @param feildValue
	 * @return
	 * @throws IOException
	 */
	public String getDynName(String urlId, String label, String value, String feildValue) {
		if (StringUtils.isNotEmpty(feildValue)) {
			//去除中括号以及双引号
			feildValue = feildValue.replaceAll(regEx, "");
			//获取远端数据
			ActionResult object = dataInterfaceService.infoToId(urlId);
			if (object.getData() != null && object.getData() instanceof DataInterfaceActionVo) {
				DataInterfaceActionVo vo= (DataInterfaceActionVo) object.getData();
				List<Map<String, Object>> dataList = (List<Map<String, Object>>) vo.getData();
				//判断是否多选
				String[] feildValues = feildValue.split(",");
				if (feildValues.length > 0) {
					//转换的真实值
					StringBuilder feildVa = new StringBuilder();
					for (String feild : feildValues) {
						for (Map<String, Object> data : dataList) {
							if (String.valueOf(data.get(value)).equals(feild)) {
								feildVa.append(data.get(label) + ",");
							}
						}
					}
					String finalValue;
					if (StringUtils.isEmpty(feildVa) || feildVa.equals("")) {
						finalValue = feildVa.toString();
					} else {
						finalValue = feildVa.substring(0, feildVa.length() - 1);
					}
					return finalValue;
				}
				for (Map<String, Object> data : dataList) {
					if (feildValue.equals(String.valueOf(data.get(value)))) {
						return data.get(label).toString();
					}
					return feildValue;
				}
			}
			return feildValue;
		}
		return feildValue;
	}

	/**
	 * 获取远端数据
	 *
	 * @param urlId
	 * @param name
	 * @param id
	 * @param children
	 * @param feildValue
	 * @return
	 */
	public String getDynName(String urlId, String name, String id, String children, String feildValue) {
		List<String> result = new ArrayList<>();
		if (StringUtils.isNotEmpty(feildValue)) {
			ActionResult object = dataInterfaceService.infoToId(urlId);
			DataInterfaceActionVo actionVo = (DataInterfaceActionVo) object.getData();
			List<Map<String, Object>> dataList = new ArrayList<>();
			if (actionVo.getData() instanceof List) {
				dataList = (List<Map<String, Object>>) actionVo.getData();
			}
			JSONArray dataAll = JsonUtil.getListToJsonArray(dataList);
			List<Map<String, String>> list = new ArrayList<>();
			treeToList(id, name, children, dataAll, list);
			String value = feildValue.replaceAll("\\[", "").replaceAll("\\]", "");
			result = list.stream().filter(t -> value.contains(String.valueOf(t.get(id)))).map(t -> String.valueOf(t.get(name))).collect(Collectors.toList());
		}
		return String.join(",", result);
	}


	/**
	 * 树转成list
	 **/
	private void treeToList(String id, String fullName, String children, JSONArray data, List<Map<String, String>> result) {
		for (int i = 0; i < data.size(); i++) {
			JSONObject ob = data.getJSONObject(i);
			Map<String, String> tree = new HashMap<>(16);
			tree.put(id, String.valueOf(ob.get(id)));
			tree.put(fullName, String.valueOf(ob.get(fullName)));
			result.add(tree);
			if (ob.get(children) != null) {
				JSONArray childArray = ob.getJSONArray(children);
				treeToList(id, fullName, children, childArray, result);
			}
		}
	}

	/**
	 * 生成单据规则
	 * @param encode
	 * @param isCache
	 * @return
	 * @throws DataException
	 */
	public String getBillNumber(String encode, Boolean isCache) throws DataException {
		return billRuleService.getBillNumber(encode, isCache);
	}



	/**
	 * 获取流程任务
	 * @param id
	 * @param columns
	 * @return
	 */
	public FlowTaskEntity getInfoSubmit(String id, SFunction<FlowTaskEntity, ?>... columns) {
		return flowTaskService.getInfoSubmit(id, columns);
	}

	public void deleteFlowTask(FlowTaskEntity flowTaskEntity) throws WorkFlowException {
		flowTaskService.delete(flowTaskEntity);
	}


}
